import { Injectable } from '@angular/core';
import { Geolocation } from '@ionic-native/geolocation';
import { removeAddressEmpty } from '../../utils/basic';

declare let BMap;
@Injectable()
export class GeolocationService {

  constructor(
    private geolocation: Geolocation,
  ) {}

  /*** 获取经纬度
  * */
  initGeolocation(): Promise<any>
  {
    return this.geolocation.getCurrentPosition();
  }

  /*** 经纬度反向解析地址
   * @param x 经度
   * @param y 纬度
   * */
  getAddress(x: number,y: number): Promise<any>
  {
    return new Promise((resolve, reject) =>{
      const point = new BMap.Point(x, y);

      //坐标转换完之后的回调函数
      const translateCallback= data=> {
        if(data.status === 0) {
          const point= data.points[0];
          const geocode = new BMap.Geocoder();
          geocode.getLocation(point, (rs)=> {
            const address = removeAddressEmpty(rs.addressComponents);
            if(!address) {
              reject('获取地址失败');
              return;
            }
            resolve(address);
          });
        }
      };

      let convertor = new BMap.Convertor();
      convertor.translate([point], 1, 5, translateCallback);
    })

  }
  // 百度地址
  getBaiduLocation()
  {
    return new Promise((resolve, reject) =>{
      const geolocation = new BMap.Geolocation();
        geolocation.getCurrentPosition((r)=> {
          debugger;
          if(!r)
          {
            reject('获取地址失败');
            return;
          }
          const x= r.point.lng, y=  r.point.lat;
          const addComp= r.address;
          const str = `${addComp.city},${addComp.district},${addComp.street}${addComp.street_number}`;
          const arr= str.split(',');
          const newArr= arr.filter(value => value);
          const address= newArr.join(',');
          resolve( {x, y ,address} )
        },{enableHighAccuracy: true})
      })
  }
}
